package com.jason.kotlin.gank

import android.app.Application
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.jason.kotlin.gank.model.GankApiResponse
import com.jason.kotlin.gank.model.GankDataBean
import com.jason.kotlin.gank.repository.GankApiImpl
import com.jason.kotlin.gank.viewmodel.GankSearchViewModel
import com.jason.library.common.base.DataWrapper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.jupiter.api.Assertions.assertEquals
import org.mockito.Mockito

/**
 * @description: GankSearchViewModelTest
 *
 * @author ChenBaoyang
 * @date 4/21/21 15:05
 */
class GankSearchViewModelTest {

    @get:Rule
    val rule = InstantTaskExecutorRule()

    private val keyword = "Android"

    private val dispatcher = TestCoroutineDispatcher()

    var response: GankApiResponse<List<GankDataBean>>? = null

    lateinit var gankApi: GankApiImpl
    lateinit var viewModel: GankSearchViewModel

    @Before
    fun setUp() {
        Dispatchers.setMain(dispatcher)
        gankApi = GankApiImpl()
        //mock 出application 来创建viewModel
        val application = Mockito.mock(Application::class.java)
        viewModel = GankSearchViewModel(application)
        //设置参数
        viewModel.keyword = "Android"
    }

    @Test
    fun search() {
        dispatcher.runBlockingTest {

            val data = TestDataGenerator.getSearchTestData()
            viewModel.loadData()
            //viewModel.initData(data)
            viewModel.data.observeForever {

                val dataWrapper : DataWrapper<List<GankDataBean>>? = viewModel.data.value
                val isEmptyList = dataWrapper?.data?.isNullOrEmpty()

                for (item in it.data!!){
                    println(item.toString())
                }

                assertEquals(false, isEmptyList)
            }
        }
    }

    @After
    fun cleanup() {
        Dispatchers.resetMain()
    }
}